import axios from 'axios';
import router from '@/router';
import Constants from '@/components/util/Constants';

//创建Axis实例
let instance = axios.create({
  timeout: 10000,
  withCredentials: true,
  headers: {
    'Cache-Control': 'no-cache',
    'Pragma': 'no-cache',
    'Content-Type': 'application/json;charset=UTF-8',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': '*',
    'Access-Control-Allow-Credentials': 'true'
  }
});

// http request 拦截器: 请求之前执行
instance.interceptors.request.use(
  config => {
    if (sessionStorage.getItem(Constants.TOKEN)) {
      config.headers.Token = sessionStorage.getItem(Constants.TOKEN);
    }
    return config;
  },
  error => {
    return Promise.reject(error)
  }
);

// http response 拦截器: 请求响应之后拦截处理
instance.interceptors.response.use(
  response => {
    switch (response.data.code) {
      case '00000': //成功
        return Promise.resolve(response.data.data);
      case '100001': //token无效，跳转登录页
        sessionStorage.removeItem(Constants.TOKEN);
        router.replace("/login");
        return Promise.reject(response);
      default:
        return Promise.reject(response);
    }
  },
  // 返回错误信息
  error => {
    console.log('error happened ==> url:[%s], message: [%s]', error.config.url, JSON.stringify(error.message));
    return Promise.reject(error)
  }
);

export default instance;
